{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\h5py\\__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "from PIL import Image\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting C:\\Users\\zdwxx\\Downloads\\Compressed\\MNIST_data\\train-images-idx3-ubyte.gz\n",
      "Extracting C:\\Users\\zdwxx\\Downloads\\Compressed\\MNIST_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting C:\\Users\\zdwxx\\Downloads\\Compressed\\MNIST_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting C:\\Users\\zdwxx\\Downloads\\Compressed\\MNIST_data\\t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# 载入数据集\n",
    "mnist = input_data.read_data_sets(r\"C:\\Users\\zdwxx\\Downloads\\Compressed\\MNIST_data\", one_hot=True)\n",
    "\n",
    "# 定义每个批次的大小\n",
    "batch_size = 100\n",
    "# 计算一共有多少个批次\n",
    "n_batch = mnist.train.num_examples // batch_size\n",
    "\n",
    "# 初始化权值函数\n",
    "def weight_variable(shape):\n",
    "    initial = tf.truncated_normal(shape, stddev=0.1) # 生成一个截断的正态分布\n",
    "    return tf.Variable(initial)\n",
    "\n",
    "# 初始化偏置值函数\n",
    "def bias_variable(shape):\n",
    "    initial = tf.constant(0.1, shape=shape)\n",
    "    return tf.Variable(initial)\n",
    "\n",
    "# 卷积层\n",
    "def conv2d(x, W):\n",
    "#   x input tensor of shape:`[filter_height * filter_wid3th * in_channels, output_channels]`.\n",
    "# `[filter_height, filter_width, in_channels, out_channels]`\n",
    "# `strides[0] = strides[3] = 1,strides[1]->x方向上的补偿，[2]->y方向上的补偿\n",
    "# padding: A string from:\"SAME\", \"VAILD\"\n",
    "    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=\"SAME\")\n",
    "\n",
    "# 池化层\n",
    "def max_pool_2x2(x):\n",
    "# ksize[1,x,y,1]\n",
    "    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"SAME\")\n",
    "\n",
    "# 定义两个placeholder\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y = tf.placeholder(tf.float32, [None, 10])\n",
    "keep_prob = tf.placeholder(tf.float32)\n",
    "\n",
    "# 改变x的格式转为4D的向量[batch, in_height, in_widch, in_channels]\n",
    "x_image = tf.reshape(x, [-1, 28, 28, 1]) # [批次，高，宽，通道]\n",
    "\n",
    "# 初始化第一个卷积层的权值和偏置值\n",
    "W_conv1 = weight_variable([5, 5, 1, 32]) # 5*5的采样窗口，32个卷积核从1个平面抽取特征\n",
    "\n",
    "b_conv1 = bias_variable([32]) # 每一个卷积核的偏置值\n",
    "\n",
    "\n",
    "\n",
    "# 把x_image的权值进行卷积，加上偏置值，然后应用于relu激活函数\n",
    "\n",
    "h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n",
    "h_pool1 = max_pool_2x2(h_conv1) # 进行max_pool\n",
    "\n",
    "\n",
    "# 初始化第二个卷积层的权值和偏置值\n",
    "W_conv2 = weight_variable([5, 5, 32, 64]) # 5*5的采样窗口，64个卷积核从32个平面抽取特征\n",
    "\n",
    "b_conv2 = bias_variable([64]) # 每一个卷积核的偏置值\n",
    "\n",
    "\n",
    "# 把x_image的权值进行卷积，加上偏置值，然后应用于relu激活函数\n",
    "h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n",
    "h_pool2 = max_pool_2x2(h_conv2) # 进行max_pool\n",
    "\n",
    "# 28*28的图片第一次卷积后还是28*28，第一次池化后变成了14*14\n",
    "# 第二次卷积后为14*14，第二次池化后变成了7*7\n",
    "# 通过上面的操作后得到了64张7*7的平面\n",
    "\n",
    "# 初始化第一个全连接层的权值\n",
    "W_fc1 = weight_variable([7*7*64, 1024])\n",
    "\n",
    "b_fc1 = bias_variable([1024])\n",
    "\n",
    "\n",
    "# 把池化层2的输出扁平化为1维\n",
    "h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\n",
    "\n",
    "# 求出第一个全连接层的输出\n",
    "h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n",
    "\n",
    "# 使用dropout防止过拟合\n",
    "h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "\n",
    "# 初始化第二个全连接层\n",
    "W_fc2 = weight_variable([1024, 10])\n",
    "\n",
    "b_fc2 = bias_variable([10])\n",
    "\n",
    "# 计算输出\n",
    "prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n",
    "\n",
    "# 交叉熵代价函数\n",
    "loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))\n",
    "\n",
    "# loss = tf.reduce_mean(tf.square(y - prediction))\n",
    "\n",
    "# Adam优化器\n",
    "train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)\n",
    "\n",
    "# 结果存放在一个布尔型列表中\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1)) #argmax返回1维张量中最大的值所在的位置\n",
    "# 求准确率\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))#cast转换类型，True->1.0, False->0.0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from C:/model/cnn_mnist/my_mnist_net.ckpt\n"
     ]
    }
   ],
   "source": [
    "writer = tf.train.Saver()\n",
    "\n",
    "writer.restore(sess, \"C:/model/cnn_mnist/my_mnist_net.ckpt\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "sess = tf.Session()\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9918"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels, keep_prob:1.0})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "结果是:2, 可能性是: 99.983%\n"
     ]
    }
   ],
   "source": [
    "img = Image.open(\"c:/learn/test.jpg\")\n",
    "img = img.convert(\"L\")\n",
    "x_img_data = (255 - np.array(img)) / 255\n",
    "x_img_data = x_img_data.reshape((1, 784))\n",
    "result = sess.run(prediction, feed_dict={x:x_img_data, y:np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).reshape((1, 10)), keep_prob:1.0})\n",
    "print(\"结果是:%d, 可能性是: %.3f%%\" % (result.argmax(), result.max() * 100))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "img = Image.open(\"c:/learn/test.jpg\")\n",
    "img = img.convert(\"L\")\n",
    "x_img_data = (255 - np.array(img)) / 255\n",
    "x_img_data = x_img_data.reshape((1, 784))\n",
    "sess.run(train_step, feed_dict={x:x_img_data, y:np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 0]).reshape((1, 10)), keep_prob:1.0})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[4, 6, 9, 1, 5, 8, 0, 3, 7, 2]], dtype=int64)"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result.argsort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
